<template>
  <div class="p-2">
    <el-row :gutter="10">
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <div><p>分类目录</p></div>
            <div>
              <el-button type="primary" plain icon="Plus" @click="UpdateTypeDialogShow"
                         v-hasPermi="['attendance:shift:add']">新增
              </el-button>
            </div>
          </div>
          <el-tree
            class="mt-2"
            ref="deptTreeRef"
            node-key="catalogueId"
            :data="groupOptions"
            :props="{ label: 'catalogueName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-contextmenu.prevent="openContextMenu"

          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                    :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="showSearch">
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
              <el-form-item label="项目名称" prop="itemsName">
                <el-input v-model="queryParams.itemsName" placeholder="请输入名称" clearable style="width: 240px"/>
              </el-form-item>
              <el-form-item label="项目类型" prop="itemsType">
                <!-- <el-select v-model="queryParams.catalogueId" placeholder="请选择计划" clearable>
                  <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select> -->
                <el-select v-model="queryParams.itemsType" placeholder="请选择">
                  <el-option
                    v-for="item in typeArr"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否评分" prop="isScore">
                <el-select v-model="queryParams.isScore" placeholder="请选择">
                  <el-option
                    v-for="item in isScoreArr"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
                <!-- <el-select v-model="queryParams.isScore" placeholder="请选择计划" clearable>
                  <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select> -->
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:group:add']">
                  新增
                </el-button>
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="multiple" @click="handleUpdateGroup()" v-hasPermi="['attendance:group:edit']"
                  >修改</el-button
                >
              </el-col> -->
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleRemoveFromGroup()" v-hasPermi="['attendance:group:remove']"
                  >删除</el-button
                >
              </el-col>
              <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:group:export']">导出</el-button>
              </el-col> -->
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table
            height="calc(100vh - 370px)"
            v-loading="loading"
            :data="groupList"
            @selection-change="handleSelectionChange"
            @row-dblclick="(row: any, column: any, event: Event) => handleUpdateGroup(row)"
            :row-key="(row) => row.itemsId "
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="编号" align="center" prop="itemsId"/>
            <el-table-column label="检查项目名称" align="center" prop="itemsName"/>
            <el-table-column label="检查项目类型" align="center" prop="itemsType">
              <template #default="scope">
            <span v-if="scope.row.itemsType=='0'">
            选择项
          </span>
                <span v-if="scope.row.itemsType=='1'">
            数字项
          </span>
                <span v-if="scope.row.itemsType=='2'">
            文本项
          </span>
                <span v-if="scope.row.itemsType=='3'">
            拍照项
          </span>
              </template>
            </el-table-column>
            <el-table-column label="是否评分" align="center" prop="studentName">
              <template #default="scope">
            <span v-if="scope.row.itemsType=='0'">
            否
          </span>
                <span v-if="scope.row.itemsType=='1'">
            是
          </span>
              </template>
            </el-table-column>
            <el-table-column label="分类目录" align="center" prop="catalogueName"/>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdateGroup(scope.row)"
                             v-hasPermi="['attendance:group:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleRemoveFromGroup(scope.row)"
                    v-hasPermi="['attendance:group:remove']"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                      v-model:limit="queryParams.pageSize" @pagination="getList"/>
        </el-card>
      </el-col>
    </el-row>
    <div v-show="showMenu" class="custom-menu">
      <ul>
        <li @click="menuItemAdd">添加子目录</li>
        <li @click="menuItemUpdate">编辑</li>
        <li @click="menuItemDelete" v-show="!currentNodeData.children">删除</li>
        <li @click="menuHide">取消</li>
      </ul>
    </div>
    <!-- 添加或修改学生识别记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="选择项" name="0" :disabled="activeName!='0' && dialog.action=='edit'">
          <el-form ref="chargeTypeRef" :model="chargeForm" :rules="rules" label-position="right"
                   label-width="120px">
            <el-form-item label="检查项目名称" prop="itemsName">
              <el-input v-model="chargeForm.itemsName" placeholder="请输入检查项目名称"/>
            </el-form-item>
            <el-form-item label="所属分类目录" prop="catalogueId">
              <el-select v-model="chargeForm.catalogueId" placeholder="请选择">
                <el-option
                  v-for="item in groupOptions"
                  :key="item.catalogueId"
                  :label="item.catalogueName"
                  :value="item.catalogueId">
                </el-option>
              </el-select>
              <!-- <el-input v-model="form.studentName" placeholder="请输入学生姓名" /> -->
            </el-form-item>
            <el-form-item label="是否允许多选" prop="xzIsChoice">
              <el-radio v-model="chargeForm.xzIsChoice" label="1">是</el-radio>
              <el-radio v-model="chargeForm.xzIsChoice" label="2">否</el-radio>
            </el-form-item>
            <el-form-item label="是否为必填项" prop="isRequired">
              <el-radio v-model="chargeForm.isRequired" label="0">是</el-radio>
              <el-radio v-model="chargeForm.isRequired" label="1">否</el-radio>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="chargeForm.remark" placeholder="请输入备注"/>
            </el-form-item>
            <el-form-item label="选项设置">
              <!--              optionBoList-->
              <div class="row-grid attrs-table">
                <div class="row-grid-header">
                  <div class="row-grid-tr">
                    <div class="row-grid-td serial">序号</div>
                    <div class="row-grid-td namemax row-grid-center">选项名称</div>
                    <div class="row-grid-td name1">选中即合格</div>
                    <div class="row-grid-td name1">不选中即合格</div>
                    <div class="row-grid-td price">选中评分</div>
                    <div class="row-grid-td name">默认选中</div>
                    <div class="row-grid-td action text-right">操作</div>
                  </div>
                </div>
                <draggable
                  class="row-grid--draggable"
                  v-model="form.optionBoList"
                  chosenClass="row-grid-tr--chosen"
                  ghostClass="row-grid-tr--ghost"
                  dragClass="row-grid-tr--drag"
                  :forceFallback="true"
                  handle=".serial"
                  @start="true"
                  @end="draggerEnd"
                >

                  <template #item="{ element,index }">
                    <div class="row-grid-tr">
                      <div class="row-grid-td serial">
                        <el-icon>
                          <Sort/>
                        </el-icon>
                        {{ element.orderNum }}
                      </div>
                      <div class="row-grid-td namemax">
                        <el-form-item>
                          <el-input v-model="element.optionName"></el-input>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td name1">
                        <el-form-item>
                          <el-checkbox true-label="1" false-label="0" v-model="element.optionPass"></el-checkbox>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td name1">
                        <el-form-item>
                          <el-checkbox true-label="1" false-label="0" v-model="element.optionNoPass"></el-checkbox>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td name">
                        <el-input  v-model.number="element.optionScore"></el-input>
                      </div>
                      <div class="row-grid-td name1">
                        <el-form-item>
                          <el-checkbox true-label="1" false-label="0" v-model="element.optionIs"></el-checkbox>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td action text-right">
                        <el-button type="text" @click="deleteOptionBoList(index)">删除</el-button>
                      </div>
                    </div>

                  </template>
                </draggable>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addOptionBoList">添加选项</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :disabled="activeName!='1' && dialog.action=='edit'" label="数字项" name="1">
          <el-form ref="numFormRef" :model="numForm" :rules="rules" label-position="right" label-width="120px">
            <el-form-item label="检查项目名称" prop="itemsName">
              <el-input v-model="numForm.itemsName" placeholder="请输入学生id"/>
            </el-form-item>
            <el-form-item label="所属分类目录" prop="catalogueId">
              <el-select v-model="numForm.catalogueId" placeholder="请选择">
                <el-option
                  v-for="item in groupOptions"
                  :key="item.catalogueId"
                  :label="item.catalogueName"
                  :value="item.catalogueId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否为必填项" prop="isRequired">
              <el-radio v-model="numForm.isRequired" label="0">是</el-radio>
              <el-radio v-model="numForm.isRequired" label="1">否</el-radio>
            </el-form-item>
            <el-form-item label="计量单位" prop="numUnit">
              <el-input v-model="numForm.numUnit" placeholder="请输入班级名称"/>
            </el-form-item>
            <el-form-item label="输入值上限" prop="numInputUpperLimit">
              <el-input-number v-model="numForm.numInputUpperLimit" @change="handleChange"
                               label="描述文字"></el-input-number>
            </el-form-item>
            <el-form-item label="输入值下限" prop="numInputLowerLimit">
              <el-input-number v-model="numForm.numInputLowerLimit" @change="handleChange"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="合格值上限" prop="numPassUpperLimit">
              <el-input-number v-model="numForm.numPassUpperLimit" @change="handleChange"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="合格值下限" prop="numPassLowerLimit">
              <el-input-number v-model="numForm.numPassLowerLimit" @change="handleChange"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="合格评分数" prop="numPassScore">
              <el-input-number v-model="numForm.numPassScore" @change="handleChange" label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="不合格评分数" prop="numPassNoScore">
              <el-input-number v-model="numForm.numPassNoScore" @change="handleChange"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="默认输入值" prop="txtDefaultValue">
              <el-input-number v-model="numForm.txtDefaultValue" @change="handleChange"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="numForm.remark" placeholder="请输入班级名称"/>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :disabled="activeName!='2' && dialog.action=='edit'" label="文本项" name="2">
          <el-form ref="textFormRef" :model="textForm" :rules="rules" label-position="right" label-width="120px">
            <el-form-item label="检查项目名称" prop="itemsName">
              <el-input v-model="textForm.itemsName" placeholder="请输入检查项目名称"/>
            </el-form-item>
            <el-form-item label="所属分类" prop="catalogueId">
              <el-select v-model="textForm.catalogueId" placeholder="请选择">
                <el-option
                  v-for="item in groupOptions"
                  :key="item.catalogueId"
                  :label="item.catalogueName"
                  :value="item.catalogueId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否为必填项" prop="isRequired">
              <el-radio v-model="textForm.isRequired" label="0">是</el-radio>
              <el-radio v-model="textForm.isRequired" label="1">否</el-radio>
            </el-form-item>
            <el-form-item label="合格判断方法" prop="txtPassJudge">
              <el-select v-model="textForm.txtPassJudge" placeholder="请选择">
                <el-option
                  v-for="item in passArr"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="合格评分数" prop="numPassScore">
              <el-input-number v-model="textForm.numPassScore" @change="handleChange" :min="1" :max="10"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="不合格评分数" prop="numPassNoScore">
              <el-input-number v-model="textForm.numPassNoScore" @change="handleChange" :min="1" :max="10"
                               label="描述文字"></el-input-number>

            </el-form-item>
            <el-form-item label="默认输入内容" prop="txtDefaultValue">
              <el-input type="textarea" v-model="textForm.txtDefaultValue" placeholder="请输入班级名称"/>

            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="textForm.remark" placeholder="请输入班级名称"/>

            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :disabled="activeName!='3' && dialog.action=='edit'" label="拍照项" name="3">
          <el-form ref="photoref" :model="photoForm" :rules="rules" label-position="right"
                   label-width="120px">
            <el-form-item label="检查项目名称" prop="itemsName">
              <el-input v-model="photoForm.itemsName" placeholder="请输入项目名称"/>
            </el-form-item>
            <el-form-item label="所属分类目录" prop="catalogueId">
              <el-select v-model="photoForm.catalogueId" placeholder="请选择">
                <el-option
                  v-for="item in groupOptions"
                  :key="item.catalogueId"
                  :label="item.catalogueName"
                  :value="item.catalogueId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="photoForm.remark" placeholder="请输入班级名称"/>

            </el-form-item>
            <el-form-item label="拍照点位设置">
              <!--              optionBoList-->
              <div class="row-grid attrs-table">
                <div class="row-grid-header">
                  <div class="row-grid-tr">
                    <div class="row-grid-td serial">序号</div>
                    <div class="row-grid-td namemax row-grid-center">名称</div>
                    <div class="row-grid-td name1">是否必须拍照</div>
                    <div class="row-grid-td name1">合格判断</div>
                    <div class="row-grid-td price">合格评分</div>
                    <div class="row-grid-td price">不合格评分</div>
                    <div class="row-grid-td action text-right">操作</div>
                  </div>
                </div>
                <draggable
                  class="row-grid--draggable"
                  v-model="photoForm.optionBoList"
                  chosenClass="row-grid-tr--chosen"
                  ghostClass="row-grid-tr--ghost"
                  dragClass="row-grid-tr--drag"
                  :forceFallback="true"
                  handle=".serial"
                  @start="true"
                  @end="draggerEnd"
                >

                  <template #item="{ element,index }">
                    <div class="row-grid-tr">
                      <div class="row-grid-td serial">
                        <el-icon>
                          <Sort/>
                        </el-icon>
                        {{ element.orderNum }}
                      </div>
                      <div class="row-grid-td namemax">
                        <el-form-item>
                          <el-input v-model="element.optionName"></el-input>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td name1">
                        <el-form-item>
                          <el-checkbox true-label="1" false-label="0" v-model="element.photographIs"></el-checkbox>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td name1">
                        <el-form-item>
                          <el-checkbox true-label="1" false-label="0" v-model="element.photographPassIs"></el-checkbox>
                        </el-form-item>
                      </div>
                      <div class="row-grid-td name">
                        <el-input  v-model.number="element.photographScore"></el-input>
                      </div>
                      <div class="row-grid-td name">
                        <el-input  v-model.number="element.photographNoScore"></el-input>
                      </div>
                      <div class="row-grid-td action text-right">
                        <el-button type="text" @click="deleteOptionBoList(index)">删除</el-button>
                      </div>
                    </div>

                  </template>
                </draggable>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addphoteBoList">添加选项</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增修改分类目录 -->
    <el-dialog :title="updateTypeDialog.title" v-model="updateTypeDialog.visible" width="500px" append-to-body>
      <el-form :model="updatetypeForm" ref="updateTypeRef" :inline="true" label-width="68px" class="search-form">
        <el-form-item label="分类名称" prop="catalogueName">
          <el-input v-model="updatetypeForm.catalogueName" placeholder="请输入名称" clearable style="width: 240px"/>
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-select v-model="updatetypeForm.parentId" placeholder="请选择">
            <el-option
              v-for="item in groupOptions"
              :key="item.catalogueId"
              :label="item.catalogueName"
              :value="item.catalogueId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="TypesubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Group" lang="ts">
import {getGroup, delGroup, addGroup, updateGroup, groupTreeSelect} from '@/api/attendance/setting/group';
import {GroupVO, GroupQuery, GroupForm} from '@/api/attendance/setting/group/types';
import {DeptVO} from '@/api/system/dept/types';
import {listClassInfo} from '@/api/office/class';
import draggable from "vuedraggable";
import api from '@/api/system/user';
import {
  studentTree,
  attendanceGroupPage as attendanceGroupStudentPage,
  editAttendanceGroup as editStudentAttendanceGroup,
  removeAttendanceGroup as removeStudentAttendanceGroup
} from '@/api/office/student';
import {
  attendanceGroupPage as attendanceGroupStaffPage,
  editAttendanceGroup as editStaffAttendanceGroup,
  removeAttendanceGroup as removeStaffAttendanceGroup
} from '@/api/office/staff';
import {
  addinspectItems,
  deleteinspectItems,
  deleteinspectItemsCatalogue,
  inspectItemsCatalogue,
  inspectioninspectItemsdetail,
  inspectioninspectItemslist,
  searchinspectItemsCatalogue,
  updateinspectItems,
  updateinspectItemsCatalogue
} from '@/api/inspection';
import {StudentRecognitionRecordForm} from '@/api/attendance/recognize/student/types';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  student_accommodation_type,
  school_post
} = toRefs<any>(proxy?.useDict('student_accommodation_type', 'school_post'));
const groupList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const groupOptions = ref<any[]>([]);
const formGroupOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const groupFormRef = ref<ElFormInstance>();
const groupLinkFormRef = ref<ElFormInstance>();
const crewLinkFormRef = ref<ElFormInstance>();
const groupType = ref('1');
const deptOptions = ref<DeptVO[]>([]);
const activeName = ref('0')
const num = ref(1)
//新增修改分类目录ref
const updateTypeRef = ref<ElFormInstance>();
const passArr = ref<any[]>([
  {
    id: "1",
    label: "始终合格"
  },
  {
    id: "2",
    label: "始终不合格"
  },
  {
    id: "3",
    label: "无内容合格"
  },
  {
    id: "4",
    label: "有内容合格"
  },
  {
    id: "5",
    label: "默认始终合格"
  },
]);
const isScoreArr = ref<any[]>([
  {
    id: "0",
    label: "否"
  },
  {
    id: "1",
    label: "是"
  },
])
const typeArr=ref<any[]>([
  {
    id:"0",
    label:"选择项"
  },
  {
    id:"1",
    label:"数字项"
  },
  {
    id:"2",
    label:"文本项"
  },
  {
    id:"3",
    label:"拍照项"
  },
])
//选择项
const chargeForm = ref<any>({
  itemsName: "",
  catalogueId: "",
  xzIsChoice: 0,
  isRequired: 0,
  remark: "",
  optionBoList: []
})
const chargeTypeRef = ref<ElFormInstance>();
//数字项
const numForm = ref<any>({
  itemsName: "",
  catalogueId: "",
  isRequired: 0,
  numUnit: undefined,
  numInputUpperLimit: 0,
  numInputLowerLimit: 0,
  numPassUpperLimit: 0,
  numPassLowerLimit: 0,
  numPassScore: 0,
  numPassNoScore: 0,
  txtDefaultValue: 0,
  remark: ""
});
//文本项
const textForm = ref<any>({
  itemsName: "",
  catalogueId: "",
  isRequired: 0,
  txtPassJudge: "",
  numPassScore: 0,
  numPassNoScore: 0,
  txtDefaultValue: "",
  remark: ""
});
//拍照项
const photoForm  = ref<any>({
  itemsName: "",
  catalogueId: "",
  remark: "",
  optionBoList: []
})
const numFormRef = ref<ElFormInstance>();
const textFormRef = ref<ElFormInstance>();
const photoref=ref<ElFormInstance>();
const classOptions = ref<any[]>([]);
const showMenu = ref(false);
const currentNodeData = ref<any>({});
const treeTransferRef = ref(); // 树形穿梭框
const fromData = ref([]); // 树形数据
const toData = ref([]); // 选中的ids数据
const transferProps = ref({value: 'id', label: 'label', children: 'children', disabled: 'disabled', pid: 'parentId'});
const attendanceMemberIds = ref<any[]>([]);
const dialog = reactive({
  visible: false,
  title: '',
  action: 'add'
});


const groupLinkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const crewLinkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
//分类目录新增修改
const UpdateTypeDialogShow = () => {
  reset();
  updatetypeForm.value.parentId = ""
  delete updatetypeForm.value.catalogueId
  // updatetypeForm.value.catalogueId=""
  updatetypeForm.value.catalogueName = ""
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改/新增分类目录';
};
//新增修改分类目录弹窗
const updateTypeDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const updatetypeForm = ref<any>({
  catalogueName: undefined,
  parentId: undefined
})
const handleClick = (e, c) => {
  // console.log("eee",e,c)

}
/**分类新增提交按钮 */
const TypesubmitForm = () => {
  updateTypeRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.log("dddddd", updatetypeForm.value)
      if (updatetypeForm.value?.catalogueId !== undefined) {
        await updateinspectItemsCatalogue(updatetypeForm.value).finally(() => (buttonLoading.value = false));
      } else {
        await inspectItemsCatalogue(updatetypeForm.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      updateTypeDialog.visible = false;
      await getGroupTree();
    }
  });
};
const initFormData: StudentRecognitionRecordForm = {
  id: undefined,
  studentId: undefined,
  studentName: undefined,
  gender: undefined,
  classId: undefined,
  className: undefined,
  gradeLevel: undefined,
  studentStatus: undefined,
  recognizeTime: undefined,
  deviceType: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  facePic: undefined,
  snapshotPic: undefined,
  comparisonScore: undefined
};
const data = reactive<any>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // studentName: undefined,
    classId: undefined,
    gradeLevel: undefined,
    studentStatus: undefined,
    deviceType: undefined,
    itemsName: undefined,
    catalogueId: undefined,
    params: {
      recognizeTime: undefined
    }
  },
  rules: {
    id: [{required: true, message: '不能为空', trigger: 'blur'}],
    studentId: [{required: true, message: '学生id不能为空', trigger: 'blur'}],
    gender: [{required: true, message: '性别不能为空', trigger: 'change'}],
    classId: [{required: true, message: '班级id不能为空', trigger: 'blur'}],
    gradeLevel: [{required: true, message: '级别不能为空', trigger: 'change'}],
    studentStatus: [{required: true, message: '学生状态不能为空', trigger: 'change'}],
    recognizeTime: [{required: true, message: '识别时间不能为空', trigger: 'blur'}],
    deviceType: [{required: true, message: '设备类型不能为空', trigger: 'change'}],
    deviceCode: [{required: true, message: '设备编码不能为空', trigger: 'blur'}],
    deviceName: [{required: true, message: '设备名称不能为空', trigger: 'blur'}],
    facePic: [{required: true, message: '图片路径不能为空', trigger: 'blur'}],
    snapshotPic: [{required: true, message: '抓拍图不能为空', trigger: 'blur'}],
    comparisonScore: [{required: true, message: '比对分值不能为空', trigger: 'blur'}],

    itemsName: [{required: true, message: '项目名称不能为空', trigger: 'blur'}],
    // txtPassJudge: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    // catalogueId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
  }
});

const {queryParams, form, rules} = toRefs(data);

const linkForm = ref<any>({});

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  if (100 === data.id) {
    return;
  }
  form.value.parentId = data.id;
  getGroup(data.id).then((resp) => {
    groupType.value = resp.data.groupType;
    const groupIds = [...resp.data.children];
    groupIds.push(data.id);
    queryParams.value.attendanceGroupIds = groupIds;
    handleQuery();
  });
};

/** 查询部门下拉树结构 */
const getGroupTree = async () => {
  const res = await searchinspectItemsCatalogue();
  groupOptions.value = res.data;
};

const searchClassInfo = (queryString, cb) => {
  listClassInfo({className: queryString}).then((response) => {
    cb(response.rows);
  });
};

/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

const openContextMenu = (event: any, nodeData: any) => {
  // 设置菜单的位置
  const menu = proxy?.$el.querySelector('.custom-menu');
  const clickX = event.clientX;
  const clickY = event.clientY;
  menu.style.left = clickX + 10 + 'px';
  menu.style.top = clickY + 'px';
  currentNodeData.value = nodeData;
  showMenu.value = true;
};

const menuItemAdd = (option: any) => {
  // showMenu.value = false;
  // handleAdd();
  console.log("ddddd1111", option)
  updatetypeForm.value.parentId = ""
  updatetypeForm.value.catalogueId = ""
  updatetypeForm.value.catalogueName = ""
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改/新增分类目录';
};

const menuItemUpdate = (option: any) => {
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改/新增分类目录';
  console.log("currentNodeData", currentNodeData)
  reset();
  Object.assign(updatetypeForm.value, currentNodeData.value);
  console.log("ddddd", updatetypeForm)
  updateTypeDialog.visible = true;
  updateTypeDialog.title = '修改分类目录';
};

const menuItemLink = (option: any) => {
  showMenu.value = false;
  handleAddLink(currentNodeData.value);
};

const menuItemDelete = async () => {
  showMenu.value = false;
  console.log("currentNodeData", currentNodeData?.value),
    await deleteinspectItemsCatalogue(currentNodeData?.value?.catalogueId);
  proxy?.$modal.msgSuccess('删除成功');
  updateTypeDialog.visible = false;
  await getGroupTree();
};

const menuHide = (option: any) => {
  showMenu.value = false;
};

/** 查询考勤分组列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  // proxy?.addDateRange(queryParams.value, dateRangeRecognizeTime.value, 'PunchTime');
  const res = await inspectioninspectItemslist(queryParams.value);
  groupList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

const cancelLink = () => {
  reset();
  groupLinkDialog.visible = false;
  crewLinkDialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  fromData.value = [];
  toData.value = [];
  linkForm.value = {};
  treeTransferRef.value?.clearData();
  groupFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.itemsId );
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(":dddddd", selection)
};

const loadFromData = async () => {
  if (groupType.value === '1') {
    const res = await studentTree();
    fromData.value = res.data;
  } else if (groupType.value === '2') {
    const res = await api.deptUserTreeSelect();
    fromData.value = res.data;
  }
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  numForm.value = {};
  textForm.value = {}
  chargeForm.value={ itemsName: "",
  catalogueId: "",
  xzIsChoice: 0,
  isRequired: 0,
  remark: "",
  optionBoList: []};
  photoForm.value={itemsName: "",
  catalogueId: "",
  remark: "",
  optionBoList: []}
  form.value = Object.assign({}, chargeForm.value);
  console.log(groupType.value, 'groupType.value')
  // form.value.parentId = groupType.value === '1' ? 101 : 102;

  await loadFromData();
  treeTransferRef.value?.initData();
  dialog.visible = true;
  dialog.action = 'add';
  dialog.title = '添加考勤分组';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GroupVO) => {
  reset();
  await loadFromData();
  treeTransferRef.value?.initData();
  const _groupId = row?.id || ids.value[0];
  const res = await getGroup(_groupId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  // dialog.action='edit';
  dialog.title = '修改考勤分组';
};

const handleUpdateGroup = async (row?: any) => {
  reset();
  if (row.itemsType == "2") {
    activeName.value = "2"
    let res = await inspectioninspectItemsdetail(row?.itemsId);
    textForm.value = res.data
  } else if (row.itemsType == "1") {
    activeName.value = "1"
    let res = await inspectioninspectItemsdetail(row?.itemsId);
    numForm.value = res.data
  }else if (row.itemsType == "0") {
    activeName.value = "0"
    let res:any = await inspectioninspectItemsdetail(row?.itemsId);
    chargeForm.value = res.data
    chargeForm.value.optionBoList=res.data.optionList
  }else if (row.itemsType == "3") {
    activeName.value = "3"
    let res:any = await inspectioninspectItemsdetail(row?.itemsId);
    photoForm.value = res.data
    photoForm.value.optionBoList=res.data.optionList
  }
  dialog.visible = true;
  dialog.title = '修改检查项目';
  dialog.action = 'edit';
};

const handleAddLink = async (row: any) => {
  reset();
  await loadFromData();
  treeTransferRef.value?.initData();
  linkForm.value.groupId = row.id;
  groupLinkDialog.visible = true;
  groupLinkDialog.title = '关联考勤人员';
};

/** 提交按钮 */
const submitForm = () => {
  numForm.value.itemsType = activeName.value
  console.log("Ffffff", activeName.value)
  if (activeName.value == "1") {
    buttonLoading.value = true;
    numForm.value.itemsType = activeName.value
    numFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        if (numForm.value.itemsId) {
          delete numForm.value.isScore;
          await updateinspectItems(numForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addinspectItems(numForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('新增成功');
        }
        dialog.visible = false;
        await getList();
      }
    });
  } else if (activeName.value == "2") {
    textForm.value.itemsType = activeName.value
    textFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (textForm.value.itemsId) {
          delete textForm.value.isScore
          await updateinspectItems(textForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addinspectItems(textForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('新增成功');
        }
        dialog.visible = false;
        await getList();
      }
    })
  }else if(activeName.value == "0") {
    chargeForm.value.itemsType = activeName.value
    chargeTypeRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (chargeForm.value.itemsId) {
          delete chargeForm.value.isScore
          await updateinspectItems(chargeForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addinspectItems(chargeForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('新增成功');
        }
        dialog.visible = false;
        await getList();
      }
    })
  }else if(activeName.value == "3") {
    photoForm.value.itemsType = activeName.value
    photoref.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (photoForm.value.itemsId) {
          delete photoForm.value.isScore
          await updateinspectItems(photoForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addinspectItems(photoForm.value).finally(() => (buttonLoading.value = false));
          proxy?.$modal.msgSuccess('新增成功');
        }
        dialog.visible = false;
        await getList();
      }
    })
  }
};

const submitGroupLinkForm = () => {
  buttonLoading.value = true;
  if (groupType.value === '1') {
    linkForm.value.studentIds = attendanceMemberIds.value;
    editStudentAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  } else {
    linkForm.value.staffIds = attendanceMemberIds.value;
    editStaffAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  }
  proxy?.$modal.msgSuccess('修改成功');
  groupLinkDialog.visible = false;
  getList();
};

const submitCrewLinkForm = () => {
  buttonLoading.value = true;
  if (groupType.value === '1') {
    editStudentAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  } else {
    editStaffAttendanceGroup(linkForm.value).finally(() => (buttonLoading.value = false));
  }
  proxy?.$modal.msgSuccess('修改成功');
  crewLinkDialog.visible = false;
  getList();
};

/** 删除按钮操作 */
const handleDelete = async (row: GroupVO) => {
  const _groupIds = row.id;
  await proxy?.$modal.confirm('是否确认删除考勤分组"' + row.label + '"？').finally(() => (loading.value = false));
  await delGroup(_groupIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getGroupTree();
};

const handleRemoveFromGroup = async (row?: any) => {
  if(!row){
    console.log("ddddddd",ids.value[0])
  await proxy?.$modal.confirm('是否确认删除选中的"' + ids?.value?.length + '"条数据？').finally(() => (loading.value = false));
  await deleteinspectItems(ids.value);
  proxy?.$modal.msgSuccess('删除成功');
  }else{
    const _ids = row?.itemsId;
    let msg = groupList.value.find((e:any) => _ids === e.itemsId)?.itemsName;
    await proxy?.$modal.confirm('是否确认删除选中的"' + msg + '"数据？').finally(() => (loading.value = false));
   await deleteinspectItems(_ids);
   proxy?.$modal.msgSuccess('删除成功');
  }
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    groupType.value === '1' ? 'office/student/attendance-group/export' : 'office/staff/attendance-group/export',
    {
      ...queryParams.value
    },
    `考勤组_${new Date().getTime()}.xlsx`
  );
};

/**
 * 将选中菜单存入表单
 * @param val 子组件穿梭框返回
 */
const checkVal = (val: any) => {
  const arr = [];
  for (const i of val) {
    if (!i.children) {
      arr.push(i.id);
    }
  }
  attendanceMemberIds.value = arr;
};


const draggerEnd = (v: any) => {
  console.log('结束啦', form.value.optionBoList);
  form.value.optionBoList.forEach((item, index) => {
    item.orderNum = index + 1;
  })
}

const addOptionBoList =()=>{
  if(activeName.value=="0"){
    form?.value?.optionBoList?.push({
    orderNum:form.value.optionBoList.length+1
  });
  }else{
    photoForm?.value?.optionBoList?.push({
    orderNum:form.value.optionBoList.length+1
  });
  }
}
const addphoteBoList =()=>{
  photoForm.value.optionBoList.push({
    orderNum:photoForm.value.optionBoList.length+1
  });
}

const deleteOptionBoList=(index)=>{
  form.value.optionBoList.splice(index,1);

  form.value.optionBoList.forEach((item, index) => {
    item.orderNum = index + 1;
  })
}


onMounted(() => {
  getDeptTree();
  getGroupTree();
  getList();
});


</script>
<style lang="scss" scoped>
@import '@/assets/styles/variables.module';

.custom-menu {
  position: fixed;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  z-index: 1000;
}

.custom-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.custom-menu ul li {
  padding: 8px 20px;
  cursor: pointer;
  font-size: 13px;
  color: $blue;
}

.custom-menu ul li:hover {
  background-color: #eee;
}

.ss-tabs {
  background-color: #fff;
}

$--border-color-lighter: #edf0f5;
$--background-color-base: #f6f6f6;
$--color-text-regular: #646666;
.row-grid {
  position: relative;
  width: 100%;
  font-size: 14px;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid $--border-color-lighter;
  border-radius: 10px;
  background-color: #fff;

  &-header {
    background-color: $--background-color-base;
  }

  &-tr {
    display: flex;
    align-items: center;
    width: 100%;

    & + .row-grid-tr {
      border-top: 1px solid $--border-color-lighter;
    }

    &--chosen {
      cursor: move;
    }

    &--ghost {
      opacity: .5;
      background-color: #f6f8fa;
    }
  }

  &-th, &-td {
    padding: 10px 16px;
    flex: auto;
    color: $--color-text-regular;
    line-height: 1.5
  }

  &-footer {
    border-top: 1px solid $--border-color-lighter;
  }

  &-empty {
    padding: 16px;
    text-align: center;
    color: $--color-text-regular;
  }

  &-right {
    text-align: right;
  }

  &-center {
    text-align: center;
  }

  &--bordered {
    .row-grid-th,
    .row-grid-td {
      & + .row-grid-th,
      & + .row-grid-td {
        border-left: 1px solid $--border-color-lighter;
      }
    }
  }
}

.attrs-table {
  width: 740px;
  line-height: 20px;
  border: 1px solid #edf0f5;

  .row-grid--draggable {
    .row-grid-tr {
      .serial {
        cursor: grab;
      }

      &--chosen {
        .serial {
          cursor: move;
        }
      }

      &--ghost {
        opacity: 0.1;
      }

      &--drag {
        border-bottom: 1px solid #edf0f5;
        background-color: #fff;
      }
    }
  }

  .row-grid-td {
    width: 160px;
    white-space: nowrap;

    &.serial {
      width: 40px;
      text-align: left;
      .sort {
        position: relative;
        color: #969999;
        vertical-align: middle;
        margin: 0 4px 0 -4px;
      }
    }

    &.name1 {
      width: 100px;
      text-align: center;
    }

    &.namemax {
      width: 300px;
    }

    &.action {
      width: 70px;
    }

    & + .row-grid-td {
      padding-left: 0;
    }
  }

  .el-form-item__error {
    display: block;
    margin: 0;
    padding-top: 5px;
  }
}
</style>
